package com.leyou.upload.service;

import com.aliyun.oss.OSS;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exceptions.LyException;
import com.leyou.upload.config.OSSProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * @author jinpei
 * @version v1.0
 * @date 2019/5/9 20:38
 * @description TODO
 **/
@Service
public class UploadService {

    private static final File IMAGE_DIR = new File("D:\\nginx-1.14.0\\html");

    private static final String IMAGE_BASE_URL = "http://image.leyou.com/";

    private static final List<String> ALLOW_IMAG_TYPE = Arrays.asList("image/jpg", "image/png", "image/jpeg");

    static {
        if (!IMAGE_DIR.exists()) {
            IMAGE_DIR.mkdirs();
        }
    }

    public String uploadImage(MultipartFile file) {
        // 文件校验
        // 1)校验文件类型
        String contentType = file.getContentType();
        if (!ALLOW_IMAG_TYPE.contains(contentType)) {
            throw new LyException(ExceptionEnum.INVALID_FILE_TYPE);
        }
        // 2)校验图片内容
        try {
            BufferedImage image = ImageIO.read(file.getInputStream());
            if (image == null) {
                throw new LyException(ExceptionEnum.INVALID_FILE_TYPE);
            }
        } catch (IOException e) {
            throw new LyException(ExceptionEnum.INVALID_FILE_TYPE);
        }
        // 1.创建文件路径
        String filename = file.getOriginalFilename();
        File dest = new File(IMAGE_DIR, filename);
        // 2.保存文件
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            throw new LyException(ExceptionEnum.FILE_UPLOAD_ERROR);
        }
        // 3.返回地址
        return IMAGE_BASE_URL + filename;
    }

    @Autowired
    private OSS client;
    @Autowired
    private OSSProperties prop;

    public Map<String, Object> getSignature() {
        try {
            long expireTime = prop.getExpireTime();
            long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
            Date expiration = new Date(expireEndTime);
            PolicyConditions policyConds = new PolicyConditions();
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, prop.getMaxFileSize());
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, prop.getDir());

            String postPolicy = client.generatePostPolicy(expiration, policyConds);
            byte[] binaryData = postPolicy.getBytes("utf-8");
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            String postSignature = client.calculatePostSignature(postPolicy);

            Map<String, Object> respMap = new LinkedHashMap<>();
            respMap.put("accessId", prop.getAccessKeyId());
            respMap.put("policy", encodedPolicy);
            respMap.put("signature", postSignature);
            respMap.put("dir", prop.getDir());
            respMap.put("host", prop.getHost());
            respMap.put("expire", expireEndTime);
            return respMap;
        }catch (Exception e){
            throw new LyException(ExceptionEnum.UPDATE_OPERATION_FAIL);
        }
    }
}